package com.auto.learning.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Observable;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.auto.learning.R;
import com.auto.learning.activity.ChangeUserHead;
import com.auto.learning.activity.LoginActivity;
import com.auto.learning.bean.BreakPointTable;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.event.listener.OnSubTipClickListener;
import com.auto.learning.net.DownLoadInfo;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpHelper;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;

public class CommonMethod {

	/**
	 * dip转为 px
	 */
	public static int dip2px(Context context, int dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	/**
	 * px 转为 dip
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 检查sd卡
	 * 
	 * @return sd卡路径
	 */
	public static boolean checkSDCardAvailable() {
		return android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
	}

	/**
	 * 获取SD卡的路径
	 * 
	 * @return null sd卡不存在
	 */
	public static String getSDPath() {
		if (checkSDCardAvailable()) {
			return (Environment.getExternalStorageDirectory()).toString();
		}
		return null;
	}
	
	public static int parseInt(String temp, int def){
		int x = def;
		try {
			x = Integer.parseInt(temp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return x;
	}

	/**
	 * toast
	 * 
	 * @param context
	 * @param err
	 */
	public static void makeNotice(Context context, String err) {
		LayoutInflater inflater = LayoutInflater.from(context);
		View layout = inflater.inflate(R.layout.toast_custom_layout, null);
		TextView title = (TextView) layout.findViewById(R.id.toast_custom_tv);
		title.setText(err);
		Toast t = new Toast(context);
		t.setGravity(Gravity.BOTTOM, 0, 80);
		t.setView(layout);
		t.setDuration(1000);
		t.show();
	}

	public static void showLoading(Context context, String str,
			boolean cancleable) {
		try {
			LoadingDialog progressDialog = new LoadingDialog(context, str);
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.setCancelable(cancleable);
			if (!progressDialog.isShowing()) {
				progressDialog.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取版本号
	 * 
	 * @param context上下文
	 * @return 版本号
	 */
	public static String getVersionName(Context context) {
		String version = "";
		try {
			// 获取packagemanager的实例
			PackageManager packageManager = context.getPackageManager();
			// getPackageName()是你当前类的包名，0代表是获取版本信息
			PackageInfo packInfo = packageManager.getPackageInfo(
					context.getPackageName(), 0);
			version = packInfo.versionName;
		} catch (Exception e) {
		}
		return version;
	}

	/**
	 * 获取手机唯一id
	 * 
	 * @param context
	 * @return
	 */
	public static String getUUID(Context context) {
		String imsi = "";
		try {
			TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			imsi = mTelephonyMgr.getSubscriberId();
			if (imsi == null || imsi.equals("")) {
				imsi = (String) SharedPreferencesUtils.getParam(context,
						HttpRequestHelper.SP_UUID, "");
				if (imsi == null || imsi.equals("")) {
					imsi = UUID.randomUUID().toString();
					SharedPreferencesUtils.setParam(context,
							HttpRequestHelper.SP_UUID, imsi);
				}
			}
		} catch (Exception e) {
			imsi = UUID.randomUUID().toString();
			SharedPreferencesUtils.setParam(context, HttpRequestHelper.SP_UUID, imsi);
		}
		
		return imsi;
	}

	/**
	 * 根据文件路径获得文件名,可以是网络路径或者本地路径
	 * 
	 * @param filePath
	 *            传入的文件路径
	 * @return
	 */
	public static String getFileName(String filePath) {
		if (filePath.contains("/")) {
			return filePath.substring(filePath.lastIndexOf("/") + 1);
		}
		return filePath;
	}

	/**
	 * 设置listview的高度,当item的高度相同时调用
	 * @param listView
	 */
	public static void setListViewHeight(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		int len2 = listAdapter.getCount();
		for (int i = 0; i < len2; i++) {
			View listItem = listAdapter.getView(0, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		LayoutParams layoutParams = listView.getLayoutParams();
		layoutParams.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(layoutParams);
	}
	
	/**
	 * 设置listview的高度,当item的高度相同时调用
	 * @param listView
	 */
	public static void setListViewHeight(ListView listView,int start) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		int tempHeight = 0;
		int len2 = listAdapter.getCount();
		if (len2 > 0) {
			View listItem = listAdapter.getView(0, null, listView);
			listItem.measure(0, 0);
			tempHeight = listItem.getMeasuredHeight();
		}
		totalHeight += tempHeight * (len2 - start);
		LayoutParams layoutParams = listView.getLayoutParams();
		if (start == 0) {
			layoutParams.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - start));
		}else {
			layoutParams.height += totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - start));
		}
		listView.setLayoutParams(layoutParams);
	}
	
	/**
	 * 设置listview的高度，当item不是等高时调用
	 * @param listView
	 */
	public static void setListViewUnSameHeight(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		int size = listAdapter.getCount();
		for (int i = 0; i < size; i++) { 
		   View listItem = listAdapter.getView(i, null, listView);
		   listItem.measure(0,0);
		   Log.d("setListViewUnSameHeight", listItem.getMeasuredHeight()+" <--> " + listView.getDividerHeight());
		   totalHeight += listItem.getMeasuredHeight();
		}
		LayoutParams layoutParams = listView.getLayoutParams();
		layoutParams.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(layoutParams);
	}
	
	/**
	 * 设置listview的高度，当item不是等高时调用
	 * @param listView
	 */
	public static void setListViewUnSameHeightContainTextView(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		int size = listAdapter.getCount();
		for (int i = 0; i < size; i++) { 
		   View listItem = listAdapter.getView(i, null, listView);
		   listItem.measure(0,0);
		   totalHeight += listItem.getMeasuredHeight();
		   Log.d("setListViewUnSameHeight", listItem.getMeasuredHeight()+" <--> " + listView.getDividerHeight());
		}
		LayoutParams layoutParams = listView.getLayoutParams();
		layoutParams.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(layoutParams);
	}
	
	public static boolean isListViewReachTopEdge(final ListView listView) {
        boolean result=false;
        if(listView.getFirstVisiblePosition()==0){
            final View topChildView = listView.getChildAt(0);
            result=topChildView.getTop()==0;
        }
        return result ;
    }
	
	
	/**
	 * 设置gridview的高度
	 * 
	 * @param listView
	 */
	public static void setGridViewHeight(GridView gridView,int numCol,int verticalSpacing) {
		ListAdapter listAdapter = gridView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		int lenL = (int) Math.ceil((double)listAdapter.getCount() / numCol);
		for (int i = 0, len = lenL; i < len; i++) {
			View listItem = listAdapter.getView(i, null, gridView);
			listItem.measure(0, 0);
			totalHeight += (listItem.getMeasuredHeight()+ verticalSpacing);
		}
		LayoutParams layoutParams = gridView.getLayoutParams();
		layoutParams.height = totalHeight;
		gridView.setLayoutParams(layoutParams);
	}

	/**
	 * 
	 * @param cotext
	 * @return 0 AS 断网 1 AS WIFI 2 AS 234G网络
	 */
	public static int getNetworkState(Context context) {
		int flag = 0;
		try {
			ConnectivityManager mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mWifi = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			NetworkInfo mMobile = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if ((mWifi != null) && ((mWifi.isAvailable()) || (mMobile != null && mMobile.isAvailable()))) {
				if (mWifi.isConnected()) {
					flag = 1;
				}else if (mMobile != null && mMobile.isConnected()) {
					flag = 2;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 验证手机号码
	 * @param phone
	 * @return
	 */
	public static boolean regExpPhone(String phone) {
		String regExp = "^((13[0-9])|(15[0-9])|(18[0-9])|(17[0-9]))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(phone);
		return m.find();
	}

	/**
	 * 缩放/裁剪图片
	 * 
	 * @param bm
	 * @param newWidth
	 * @param newHeight
	 * @return
	 */
	public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
		// 获得图片的宽高
		int width = bm.getWidth();
		int height = bm.getHeight();
		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片
		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
				true);
		return newbm;
	}

	/**
	 * 保存图片到sd卡
	 * 
	 * @param photoBitmap图片对象
	 * @param photoName图片保存名称
	 * @param path图片保存路径
	 */
	public static void savePhotoToSDCard(Bitmap photoBitmap, String photoName) {
		String path = CommonMethod.getSDPath() + DownLoadInfo.HEAD_DIR;
		if (checkSDCardAvailable()) {
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			File photoFile = new File(path, "/" + photoName + ".png");
			if (photoFile.exists()) {
				photoFile.delete();
			}
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap != null) {
					if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,
							fileOutputStream)) {
						fileOutputStream.flush();
						fileOutputStream.close();
					}
				}
			} catch (FileNotFoundException e) {
				photoFile.delete();
				e.printStackTrace();
			} catch (IOException e) {
				photoFile.delete();
				e.printStackTrace();
			} finally {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 上传图片文件
	 */
	public static String uploadImageFile(Context context, Handler handler,String imagePath,int success,int fail){
		HttpPost httppost = new HttpPost(HttpCommonInfo.URL + HttpCommonInfo.REQ_RESOURCE_UPLOAD);
		String err = "";
		String resourceUrl = "";
		int isOK = 1;
		HttpParams httpParameters;
		try {
			httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
			HttpConnectionParams.setSoTimeout(httpParameters, 3000);
			HttpClient client = new DefaultHttpClient(httpParameters);
			MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			reqEntity.addPart(HttpCommonInfo.REQ_RESOURCE_UPLOAD_USERID,new StringBody(AES.encrypt(""+SharedPreferencesUtils.getParam(context, HttpRequestHelper.USERID, 0))));
			reqEntity.addPart(HttpCommonInfo.REQ_RESOURCE_UPLOAD_RESOURCETYPE, new StringBody(AES.encrypt("1")));
			File picPath = new File(imagePath);
			reqEntity.addPart(HttpCommonInfo.REQ_RESOURCE_UPLOAD_FILEUPLOADVOUPLOAD, new FileBody(picPath, AES.encrypt(getFileName(imagePath)), "*/image", "utf-8"));
			httppost.setEntity(reqEntity);
			HttpResponse response = client.execute(httppost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(response.getEntity());
				result = AES.decrypt(result);
				JSONObject jObject = new JSONObject(parseResultJson(result));
				int errCode = jObject.getInt(HttpCommonInfo.RESULT_CODE);
				if (errCode == 0) {
					isOK = 0;
					JSONObject jsonObject = new JSONObject(parseDataJson(result));
					resourceUrl = jsonObject.getString(HttpCommonInfo.RES_RESOURCE_UPLOAD_RESOURCEURL);
				} else {
					isOK = 1;
					err = jObject.getString(HttpCommonInfo.RESULT_MSG);
				}
			} else {
				err = context.getString(R.string.connect_err_unkonw);
				isOK = 1;
			}
		} catch (ClientProtocolException e) {
			err = context.getString(R.string.connect_err_unkonw);
			isOK = 1;
		} catch (IOException e) {
			err = context.getString(R.string.connect_err_io);
			isOK = 1;
		} catch (Exception e) {
			err = context.getString(R.string.connect_err_unkonw);
			isOK = 1;
		} finally {
			switch (isOK) {
			case 0:
				Message msga = handler.obtainMessage(success);
				msga.obj = resourceUrl;
				handler.sendMessage(msga);
				break;
			case 1:
				Message msgb = handler.obtainMessage(fail);
				msgb.obj = err;
				handler.sendMessage(msgb);
				break;
			}
		}
		return resourceUrl;
	}
	
	
	public static void uploadFile(Context context, int type, Handler handler,
			long speechTime) {
		HttpPost httppost = new HttpPost(HttpCommonInfo.URL
				+ HttpCommonInfo.REQ_RESOURCE_UPLOAD);
		String mp3Path = getSDPath() + DownLoadInfo.MAIN_DIR;
		String picPath = getSDPath() + DownLoadInfo.HEAD_DIR;
		String err = "";
		String resourceUrl = "";
		int isOK = 1;
		HttpParams httpParameters;
		try {
			httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
			HttpConnectionParams.setSoTimeout(httpParameters, 3000);
			HttpClient client = new DefaultHttpClient(httpParameters);
			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			reqEntity.addPart(
					HttpCommonInfo.REQ_RESOURCE_UPLOAD_USERID,
					new StringBody(AES.encrypt(""+SharedPreferencesUtils.getParam(context, HttpRequestHelper.USERID, 0))));
			reqEntity.addPart(HttpCommonInfo.REQ_RESOURCE_UPLOAD_RESOURCETYPE,
					new StringBody(AES.encrypt("" + type)));
			if (type == 1) {// 图片
				reqEntity.addPart(
						HttpCommonInfo.REQ_RESOURCE_UPLOAD_FILEUPLOADVOUPLOAD,
						new FileBody(new File(picPath, "myhead.png"), AES
								.encrypt("myhead.png"), "*/image", "utf-8"));
			} else if (type == 2) {// MP3
				reqEntity.addPart(
						HttpCommonInfo.REQ_RESOURCE_UPLOAD_FILEUPLOADVOUPLOAD,
						new FileBody(new File(mp3Path, "temp.mp3"), AES
								.encrypt("temp.mp3"), "audio/mp3", "utf-8"));
			}
			httppost.setEntity(reqEntity);
			HttpResponse response = client.execute(httppost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(response.getEntity());
				result = AES.decrypt(result);
				JSONObject jObject = new JSONObject(parseResultJson(result));
				int errCode = jObject.getInt(HttpCommonInfo.RESULT_CODE);
				if (errCode == 0) {
					isOK = 0;
					JSONObject jsonObject = new JSONObject(parseDataJson(result));
					resourceUrl = jsonObject
							.getString(HttpCommonInfo.RES_RESOURCE_UPLOAD_RESOURCEURL);
				} else {
					isOK = 1;
					err = jObject.getString(HttpCommonInfo.RESULT_MSG);
				}
			} else {
				err = context.getString(R.string.connect_err_unkonw);
				isOK = 1;
			}
		} catch (ClientProtocolException e) {
			err = context.getString(R.string.connect_err_unkonw);
			isOK = 1;
		} catch (IOException e) {
			err = context.getString(R.string.connect_err_io);
			isOK = 1;
		} catch (Exception e) {
			err = context.getString(R.string.connect_err_unkonw);
			isOK = 1;
		} finally {
			switch (isOK) {
			case 0:
				Message msga = handler.obtainMessage(ChangeUserHead.PUBLIC_SENDAUDIO_SUCCESS);
				msga.obj = resourceUrl;
				Bundle bundle = new Bundle();
				bundle.putLong("doneTime", speechTime);
				msga.setData(bundle);
				handler.sendMessage(msga);
				break;
			case 1:
				Message msgb = handler.obtainMessage(ChangeUserHead.PUBLIC_SENDAUDIO_FAIL);
				msgb.obj = err;
				handler.sendMessage(msgb);
				break;
			}
		}
	}
	
	/**
	 * 上传头像58
	 */
	public static void updataHead(Context context, String faceUrl,
			Handler handler) {
		String err = "";
		int isOK = 1;
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(
					HttpCommonInfo.REQ_FACE_URL_USERID, ""+SharedPreferencesUtils.getParam(context, HttpRequestHelper.USERID, 0)));
			params.add(new BasicNameValuePair(
					HttpCommonInfo.REQ_FACE_URL_FACEURL, faceUrl));
			HttpEntity entity = HttpHelper.getInfoByPost(
					HttpCommonInfo.REQ_FACE_URL, params, context);
			String result = HttpHelper.entity2String(entity);
			JSONObject jObject = new JSONObject(parseResultJson(result));
			int resultCode = jObject.getInt(HttpCommonInfo.RESULT_CODE);
			if (resultCode == 0) {
				isOK = 0;
			} else {
				isOK = 1;
				err = jObject.getString(HttpCommonInfo.RESULT_MSG);
			}
		} catch (ClientProtocolException e) {
			isOK = 1;
			err = context.getString(R.string.connect_err_unkonw);
		} catch (IOException e) {
			err = context.getString(R.string.connect_err_io);
			isOK = 1;
		} catch (Exception e) {
			err = context.getString(R.string.connect_err_unkonw);
			isOK = 1;
		} finally {
			switch (isOK) {
			case 0:
				Message msga = handler
						.obtainMessage(ChangeUserHead.PUBLIC_UPDATAHEAD_SUCCESS);
				handler.sendMessage(msga);
				break;
			case 1:
				Message msgb = handler
						.obtainMessage(ChangeUserHead.PUBLIC_UPDATAHEAD_FAIL);
				msgb.obj = err;
				handler.sendMessage(msgb);
				break;
			}
		}
	}
	
	public static String parseResultJson(String result) throws JSONException {
		JSONObject jObject = new JSONObject(result);
		result = jObject.getString(HttpCommonInfo.RESULT);
		return result;
	}
	
	public static String parseDataJson(String result) throws JSONException {
		JSONObject jObject = new JSONObject(result);
		result = jObject.getString(HttpCommonInfo.DATA);
		return result;
	}
	
	public static String calculationNum(int size){
		DecimalFormat format = new DecimalFormat("#.00");
		double m_size = ((double)size) / (1024*1024);
		return format.format(m_size);
	}
	
	public static String calculationMoney(int money){
		DecimalFormat format = new DecimalFormat("#.00");
		double m_size = ((double)money) / 100;
		return format.format(m_size);
	}
	
	public static boolean checkUserLogin(final Activity context, String msg) {
		boolean flag = true;
		if (TextUtils.isEmpty(MyUserInfo.getInstance().getUserInfoBean().getSessionId())) {
			flag = false;
			CommonAlertDialog alertDialog = new CommonAlertDialog(context);
			if (TextUtils.isEmpty(msg)) {
				alertDialog.setTextMessage(context.getResources().getString(R.string.text_no_login));
			}else {
				alertDialog.setTextMessage(msg);
			}
			alertDialog.setShowTitle(true);
			String[] a = {context.getResources().getString(R.string.text_goto_login),context.getResources().getString(R.string.app_cancel)};
			alertDialog.setBtns(new DialogListener() {
				
				@Override
				public void otherButtonClick(Dialog dialog) {
					dialog.dismiss();
				}
				
				@Override
				public void okButtonClick(Dialog dialog) {
					dialog.dismiss();
					Intent intent = new Intent(context, LoginActivity.class);
					context.startActivityForResult(intent, 100);
				}
				
				@Override
				public void cancelButtonClick(Dialog dialog) {
					dialog.dismiss();
				}
			},a);
			alertDialog.show();
		}
		return flag;
	}
	
	/**
	 * 检查用户是否登录
	 */
	public static boolean checkUserLogin(final Activity context){
		return checkUserLogin(context, "");
	}
	
	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}
	
	public static Bitmap readBitMap(String mPath){
		if (TextUtils.isEmpty(mPath)) {
			return null;
		}
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		File file =  new File(mPath);
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BitmapFactory.decodeStream(inputStream, null, opt);
	}	
	/**
	 * 判断是否在后台
	 * @param context
	 * @return
	 */
	public static boolean isBackground(Context context) {  
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);  
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();  
        for (RunningAppProcessInfo appProcess : appProcesses) {  
            if (appProcess.processName.equals(context.getPackageName())) {  
                if (appProcess.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {  
                    return true;  
                } else {  
                    return false;  
                }  
            }
        }  
        return false;  
    } 
	
	/**
	 * 取消闹钟
	 * @param context
	 */
	public static void cancelAlarm(Context context){
		SharedPreferencesUtils.setParam(context, HttpRequestHelper.M_TILE_WNEN_CLOSE, "");
		Intent intent = new Intent(HttpRequestHelper.ALARM_ACTION);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
        am.cancel(sender);
	}
	
	//设置闹钟
	public static void setAlarm(Context context){
		if ((boolean)SharedPreferencesUtils.getParam(context, HttpRequestHelper.M_TILE_OFF, false)) {
			AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
	        Intent intent = new Intent(HttpRequestHelper.ALARM_ACTION);
	        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
	        int value = (int) SharedPreferencesUtils.getParam(context, HttpRequestHelper.M_TILE_VALUE, 30);
	        Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.MINUTE, value);
			SharedPreferencesUtils.setParam(context, HttpRequestHelper.M_TILE_WNEN_CLOSE, DateUtil.convertToFormat(new Date(calendar.getTimeInMillis())));
//		    CommonMethod.makeNotice(context, "设置闹钟啦，时间是：" + DateUtil.convertToFormat(new Date(calendar.getTimeInMillis())));
		    Log.d("alarm", "设置闹钟啦，时间是：" + DateUtil.convertToFormat(new Date(calendar.getTimeInMillis())));
	        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
		}
	}
	
	/**
	 * 获取栈顶activity Name
	 * @param context
	 * @return
	 */
	public static String getTopActivityName(Context context) {
		String topActivityName = null;
		ActivityManager activityManager = (ActivityManager) (context.getSystemService(android.content.Context.ACTIVITY_SERVICE));
		List<RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
		if (runningTaskInfos != null) {
			ComponentName f = runningTaskInfos.get(0).topActivity;
			
			String topActivityClassName = f.getClassName(); 
			String temp[] = topActivityClassName.split("\\.");
			topActivityName = temp[temp.length - 1];
			System.out.println("topActivityName=" + topActivityName);
		}
		return topActivityName;
	}
	
	/**
	 * 显示在移动网络时提醒
	 */
	public static void showMobileNetTips(Context context,DialogListener listener){
		HttpCommonInfo.M_NET_DIALOG_SHOW = true;
		CommonAlertDialog alertDialog = new CommonAlertDialog(context);
		alertDialog.setTextMessage(context.getResources().getString(R.string.text_no_wifi));
		alertDialog.setShowTitle(true);
		String[] a = {"继续","取消"};
		alertDialog.setBtns(listener, a);
		alertDialog.show();
	}
	
	/**
	 * @param context
	 * @param a
	 * @param msg
	 * @param listener
	 */
	public static void showDialog(Context context, String[] a, String msg, DialogListener listener){
		showDialog(context, a, msg, listener, "", null);
	}
	/**
	 * @param context
	 * @param a
	 * @param msg
	 * @param listener
	 * @param showDialogClose  是否显示上面的关闭按钮
	 */
	public static void showDialog(Context context, String[] a, String msg, DialogListener listener,boolean showDialogClose){
		showDialog(context, a, msg, listener, "", "", null, showDialogClose);
	}
	
	/**
	 * @param context
	 * @param a
	 * @param msg
	 * @param title
	 * @param listener
	 */
	public static void showDialog(Context context, String[] a, String msg, String title, DialogListener listener){
		showDialog(context, a, msg, listener, title, "", null, false);
	}
	
	/**
	 * @param context
	 * @param a
	 * @param msg
	 * @param listener
	 * @param subText
	 * @param onSubTipClickListener
	 */
	public static void showDialog(Context context, String[] a, String msg, DialogListener listener,String subText, OnSubTipClickListener onSubTipClickListener){
		showDialog(context, a, msg, listener, "", subText, onSubTipClickListener, false);
	}
	
	/**
	 * 显示Dialog
	 */
	public static void showDialog(Context context, String[] a, String msg, DialogListener listener,String title, String subText, OnSubTipClickListener onSubTipClickListener, boolean showDialogClose){
		CommonAlertDialog alertDialog = new CommonAlertDialog(context);
		alertDialog.setTextMessage(msg);
		alertDialog.setShowTitle(true);
		if (!TextUtils.isEmpty(title)) {
			alertDialog.setTilte(title);
		}
		alertDialog.setShowDialogClose(showDialogClose);
		alertDialog.setBtns(listener, a);
		if (!TextUtils.isEmpty(subText)) {
			alertDialog.setSubText(subText);
			alertDialog.setOnSubTipClickListener(onSubTipClickListener);
		}
		alertDialog.show();
	}
	
	/**
	 * 极光推送设置别名和标签
	 * @param userId
	 */
	public static void setAliasAndTags(final Context context, int userId) {
		if (userId == 0) {
			userId = (int) SharedPreferencesUtils.getParam(context, HttpRequestHelper.USERID, 0);
		}
		if (userId > 0) {
			Set<String> tags = new HashSet<String>();
			tags.add(CommonMethod.getVersionName(context).replace(".", "_"));
			if (!HttpCommonInfo.URL.contains("dev")) {
				tags.add("distribute");
			}else {
				tags.add("develop");
			}
			final int tempUserId = userId;
			JPushInterface.setAliasAndTags(context, "AutoLearning_" + userId, tags , new TagAliasCallback() {
				
				@Override
				public void gotResult(int responseCode , String arg1, Set<String> arg2) {
					switch (responseCode ) {
					case 0: 	 //Success
						break;
					case 6002:  //重试
						setAliasAndTags(context, tempUserId);
						break;
					case 6011:  //连续10次频繁操作
						break;
					}
				}
			});
		}
	}
	
	
	/**
	 * APP启动时户信息JSON数据
	 * @param context
	 * @param jsonData
	 */
	@SuppressWarnings("static-access")
	public static void saveUserBaseInfo(Context context, String jsonData) {
		try {
			FileOutputStream fos = context.openFileOutput(DownLoadInfo.USER_BASE_INFO, context.MODE_PRIVATE);
			fos.write(jsonData.getBytes());
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取本地用户基本信息
	 * @param context
	 * @param tag 要查询的字段
	 * @return
	 */
	public static String readUserBaseInfo(Context context, String tag) {
		String result = null;
		try {
			FileInputStream fis = context.openFileInput(DownLoadInfo.USER_BASE_INFO);
			int length = fis.available();
			byte[] buffer = new byte[length];
			fis.read(buffer);
			String jsonData = EncodingUtils.getString(buffer, "UTF-8");
			fis.close();
			if (jsonData != null) {
				JSONObject jObject = new JSONObject(jsonData);
				result = jObject.getString(tag);
			}
		} catch (FileNotFoundException e) {
			result = null;
		} catch (IOException e) {
			result = null;
		} catch (JSONException e) {
			result = null;
		}
		return result;
	}
	
	
	public static String readAllUserInfo(Context context){
		String result = null;
		try {
			FileInputStream fis = context.openFileInput(DownLoadInfo.USER_BASE_INFO);
			int length = fis.available();
			byte[] buffer = new byte[length];
			fis.read(buffer);
			result = EncodingUtils.getString(buffer, "UTF-8");
			fis.close();
		} catch (FileNotFoundException e) {
			result = null;
		} catch (IOException e) {
			result = null;
		} 
		return result;
	}
	
	@SuppressLint("NewApi") 
	@SuppressWarnings("deprecation")
	public static void setBackground(View view,Drawable drawable){
		if (Build.VERSION.SDK_INT >= 16) {
			view.setBackground(drawable);
		}else {
			view.setBackgroundDrawable(drawable);
		}
	}
	
	/**
	 * 上传断点记录
	 */
	public static void recordBreakPoint(){
		try {
			String content = new Gson().toJson(TemporaryVariable.breakPiontMap);
			BreakPointTable breakPoint = new BreakPointTable();
			breakPoint.setId(1);
			breakPoint.setContent(content);
			breakPoint.setCreateTime(new Date());
			StaticReference.mutilDBSupport.getDao(BreakPointTable.class).createOrUpdate(breakPoint);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 记录在线播放时，点击取消时的逻辑
	 */
	public static void reordPlayStatus(Context context, int bookId, boolean showNetTips){
		if (bookId != MusicPlayManager.getInstance(context).isPlayingBookId()[0]) {
			MusicPlayManager.getInstance(context).setShowNetTips(false);
		}
	}
	public static  int getStatusHeight(Activity activity){  
	    int statusHeight = 0;  
	    Rect localRect = new Rect();  
	    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);  
	    statusHeight = localRect.top;  
	    if (0 == statusHeight){  
	        Class<?> localClass;  
	        try {  
	            localClass = Class.forName("com.android.internal.R$dimen");  
	            Object localObject = localClass.newInstance();  
	            int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());  
	            statusHeight = activity.getResources().getDimensionPixelSize(i5);  
	        } catch (ClassNotFoundException e) {  
	            e.printStackTrace();  
	        } catch (IllegalAccessException e) {  
	            e.printStackTrace();  
	        } catch (InstantiationException e) {  
	            e.printStackTrace();  
	        } catch (NumberFormatException e) {  
	            e.printStackTrace();  
	        } catch (IllegalArgumentException e) {  
	            e.printStackTrace();  
	        } catch (SecurityException e) {  
	            e.printStackTrace();  
	        } catch (NoSuchFieldException e) {  
	            e.printStackTrace();  
	        }  
	    }  
	    return statusHeight;  
	}  
	/**
	 * 时间转换
	 * @param nowDuration
	 * @return
	 */
	public static String getNowTime(int nowDuration) {
		String sendmin = null;
		int nowTime = nowDuration / 1000;
		int min = nowTime / 60;
		int sec = nowTime % 60;
		if (min < 10) {
			sendmin = "0" + min;
		} else {
			sendmin = min + "";
		}
		if (sec < 10) {
			return sendmin + ":0" + sec;
		} else {
			return sendmin + ":" + sec;
		}
	}
	public static  String formDate(String date){
		return parseData(getPreviousYear(date)) +"--" + parseData(date);
	}
	private static String parseData(String date){
		String result = "";
		if (!TextUtils.isEmpty(date)) {
			Date m_date = DateUtil.strConvertDate2(date);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 M 月 d 日");
			result = sdf.format(m_date);
		}
		return result;
	}
	private static String getPreviousYear(String date){
		String result = "";
		String[] temp = date.split("-");
		if (temp.length == 3) {
			try {
				int x = Integer.parseInt(temp[0]) - 1;
				result = x + "-" + temp[1] + "-" + temp[2];
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}
